package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.AdUserService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Override
    public ResponseResult login(AdUserDto dto) {
        //1.参数校验
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码不能为空");
        }
//        Wrapper wrapper = new QueryWrapper<AdUser>();
//        ((QueryWrapper) wrapper).eq("name", dto.getName());

        QueryWrapper<AdUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AdUser::getName,dto.getName());

        List<AdUser> list = this.list(wrapper);
        if (list!=null&&list.size()>0){
            AdUser adUser = list.get(0);         //从数据库查询出来的用户    加密密码    盐值

            String newPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());
//            新生成的密码  和  数据库加密后的密码比较
            if (adUser.getPassword().equals(newPwd)){
//                正确  生成token
                Map<String, Object> map = Maps.newHashMap();
                map.put("token",AppJwtUtil.getToken(adUser.getId().longValue()));
                adUser.setPassword("");
                adUser.setSalt("");
                map.put("user",adUser);
                return ResponseResult.okResult(map);
            }else {
//                输入错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.AD_USER_DATA_NOT_EXIST);
        }

    }

}
